package com.qiuguo.rtsp.controller;

import com.qiuguo.rtsp.service.StreamService;
import com.qiuguo.rtsp.utils.PropertyValueUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;

@Slf4j
@Controller
public class StreamController {

    private final StreamService streamService;

    public StreamController(StreamService streamService) {
        this.streamService = streamService;
    }

    @PostMapping("/stream/start")
    @ResponseBody
    public String startStream(@RequestParam String filename, @RequestParam(required = false) String rtspUrl) {
        log.info("请求启动流转换任务，文件名: {}", filename);
        
        // 如果没有提供 RTSP URL，使用配置中的默认值
        if (rtspUrl == null || rtspUrl.isEmpty()) {
            rtspUrl = PropertyValueUtils.getRtspUrl();
        }
        
        // 启动流转换任务
        String hlsUrl = streamService.startStreaming(filename, rtspUrl);
        log.info("流转换任务启动完成，文件名: {}，HLS地址: {}", filename, hlsUrl);
        
        // 返回播放页面，使用当前服务器的IP和端口
        return String.format(
            "<iframe src=\"https://m3u8player.org/player.html?url=%s\"></iframe>",
            hlsUrl
        );
    }

    @PostMapping("/stream/stop")
    @ResponseBody
    public String stopStream(@RequestParam String filename) {
        log.info("请求停止流转换任务，文件名: {}", filename);
        
        boolean success = streamService.stopStreaming(filename);
        
        if (success) {
            log.info("流转换任务停止成功，文件名: {}", filename);
            return String.format("任务 %s 已成功停止", filename);
        } else {
            log.warn("流转换任务停止失败，文件名: {} 不存在或已停止", filename);
            return String.format("任务 %s 不存在或已停止", filename);
        }
    }
    
    @GetMapping("/stream/tasks")
    @ResponseBody
    public Map<String, Boolean> getTasks() {
        log.info("请求获取当前运行的任务列表");
        return streamService.getRunningTasks();
    }
    
    @GetMapping("/stream/task-info")
    @ResponseBody
    public Map<String, StreamService.TaskInfo> getTaskInfo() {
        log.info("请求获取当前运行的任务详细信息");
        return streamService.getRunningTaskInfo();
    }

    @GetMapping("/stream")
    @ResponseBody
    public String getStream() {
        log.info("访问视频流页面");
        // 获取当前服务器的HLS URL
        String hlsUrl = "http://" + streamService.getServerIp() + ":" + streamService.getServerPort() + "/hls/stream.m3u8";
        return String.format("<iframe src=\"https://m3u8player.org/player.html?url=%s\"></iframe>", hlsUrl);
    }
    
    @GetMapping("/manager")
    public ModelAndView managerPage() {
        log.info("访问任务管理页面");
        return new ModelAndView("manager.html");
    }
}